from django.shortcuts import render,reverse
from django.http import HttpResponse,JsonResponse
from .. import models
from django.core.paginator import Paginator
from django.db.models import Q

def selectAllTypes():
	#select * from myadmin_branchtype
	#额外查询一个由path和id组成的paths字段，用paths字段排序
	data = models.Branchtype.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
	#根据','对子类进行缩进
	for x in data:
		num = x.path.count(',')-1
		x.sb = '|----'*num
		#父类名称
		if x.pid != 0:
			x.pname = models.Branchtype.objects.get(id=x.pid).name
	#select *,concat(path,id) as paths from myadmin_booktype order by paths;

	return data

# Create your views here.
# 创建后台页面的视图方法index
#后台部门管理
def index(request):
	#获取所有的图书分类
	data = selectAllTypes()

	#接受搜索条件
	selecttype = request.GET.get('selecttype',None)
	keywords = request.GET.get('keywords',None)
	if selecttype:
		#有搜索条件
		if selecttype == 'all':
			#按照多字段进行条件搜索
			data = data.filter(Q(name__contains=keywords)) #|Q(pname__contains=keywords)
		else:
			serdata = {f'{selecttype}__contains':keywords}
			data = data.filter(**serdata)

 
	#实例化分页对象，参数1，数据集；参数2，每页显示的条数
	p = Paginator(data,2)

	#接受当前的页码数
	inx_p = request.GET.get('page',1)

	#获取当前页的数据
	branchlist = p.page(inx_p)

	#分配数据
	context = {'data':branchlist}
	return render(request,'myadmin/branch/index.html',context)


#后台部门添加管理
def add(request):
	#当前所有的图书分类
	data = selectAllTypes()
	context = {'data':data}
	return render(request,'myadmin/branch/add.html',context)


#部门分类 执行添加
def insert(request):
	data = request.POST.dict()
	data.pop('csrfmiddlewaretoken')
	#判断当前的分类是否为顶级分类
	if data['pid']=='0':
		#顶级分类
		data['path']='0,'
	else:
		#子类
		#查询当前选择的父类的path
		path = models.Branchtype.objects.get(id=data['pid']).path
		data['path'] = path + data['pid']+','										

	try:
		#执行数据的添加
		obj=models.Branchtype(**data)
		obj.save()
		url = reverse('myadmin_branch_index')
		return HttpResponse(f'<script>alert("部门分类添加成功");location.href="{url}"</script>')
	except:
		url=reverse('myadmin_branch_add')
		return HttpResponse(f'<script>alert("部门分类添加失败");location.href="{url}"</script>')


#部门分类 删除
def delete(request):
	#获取分类id
	id = request.GET.get('id')
	# 获取当前的分类对象
	# obj = models.Branchtype.objects.get(id=id)

	#判断当前类下是否还有子类
	num = models.Branchtype.objects.filter(pid=id).count()
	if num:
		#不能删除
		return JsonResponse({'code':1,'msg':'当前部门下还有字类，不能删除'})

	#判断当前部门是否还有员工
	# if staffnum:
	# 	#不能删除
	# 	return JsonResponse({'code':2,'msg':'当前部门还有员工，不能删除'})

	try:
		#获取当前的部门对象
		obj = models.Branchtype.objects.get(id=id)
		obj.delete()
		return JsonResponse({'code':0,'msg':'删除成功'})
	except:
		return JsonResponse({'code':3,'msg':'删除失败'})


#部门分类 编辑
def edit(request):
	try:
		#获取id
		id = request.GET.get('id')
		name = request.GET.get('name')

		#获取当前对象
		obj = models.Branchtype.objects.get(id=id)
		obj.name = name
		obj.save()
		return JsonResponse({'code':0,'msg':'更新成功'})
	except:
		return JsonResponse({'code':1,'msg':'更新失败'})
 
